/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <strings.h>
#include <string.h>
#include <time.h>
#include <netinet/in.h>
#include <sys/time.h>
#define TAMVET 1000

void error(char *msg)
{
    perror(msg);
    exit(1);
}

/*
	Funcao que envia o vetor[1000] para os clientes que imprimirão os valores
*/
void enviar(int buffern[TAMVET])
{
	int sockfd, portno, n;
	int numero,i;
	char* host[8];
	char* port[8];
	int buffer[TAMVET];	

	host[0]="node2";
	host[1]="node4";
	host[2]="node5";
	host[3]="node6";
	host[4]="node7";
	host[5]="node8";
	host[6]="node9";
	host[7]="node10";

	port[0]="4000";
	port[1]="4001";
	port[2]="4002";
	port[3]="4003";
	port[4]="4004";
	port[5]="4005";
	port[6]="4006";
	port[7]="4007";

	struct sockaddr_in serv_addr;
	struct hostent *server;	
	int k;
	
	/* 8 Clientes receberao os dados do vetor[1000] */
	for(k=0;k<8;k++)
	{
		portno = atoi(port[k]);
		sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Config. Socket */
		if (sockfd < 0) 
			error("ERROR opening socket\n");
		server = gethostbyname(host[k]);
		if (server == NULL) {
			fprintf(stderr,"ERROR, no such host\n");
			exit(0);
		}

		bzero((char *) &serv_addr, sizeof(serv_addr));
		serv_addr.sin_family = AF_INET;
		bcopy((char *)server->h_addr, 
		(char *)&serv_addr.sin_addr.s_addr,	
		server->h_length);
		serv_addr.sin_port = htons(portno);
		if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
			error("ERROR connecting\n");

		printf("Enviando valores\n");	

		n = write(sockfd,buffern,sizeof(buffer));
		if (n < 0) 
			error("ERROR writing to socket\n");
		
	}
	
}

/*
	Implementacao Bubble Sort p/ ordenar o vetor
*/
void sort(int *buffern)
{
	struct timeval inicio, final;
 	long temposort;
	int j,i,aux;
	int k=TAMVET-1;
		
	gettimeofday(&inicio,NULL);
	for(i=0;i<TAMVET;i++)
	{
		for(j=0;j<k;j++)
		{
			if(buffern[j]>buffern[j+1])
			{
				aux=buffern[j];
				buffern[j]=buffern[j+1];
				buffern[j+1]=aux;
			}

		}
		k--;
	}
	gettimeofday(&final, NULL);
	temposort = (final.tv_sec-inicio.tv_sec)*1000000 + final.tv_usec-inicio.tv_usec; /* Tempo calculado da ordenacao do vetor */
	printf("tempo sort(ms): %lu\n", temposort);  
}

int main(int argc, char *argv[])
{
	struct timeval inicio, final;
 	long temposort;
	int sockfd, newsockfd, portno, clilen;
	int buffer[2][TAMVET/2],buffern[TAMVET],buffercopy[TAMVET],i,flag=0;
	struct sockaddr_in serv_addr, cli_addr;
	int n;
	if (argc < 2) {
		fprintf(stderr,"ERROR, no port provided\n");
		exit(1);
	}
	sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Configuraçao do socket */
	if (sockfd < 0) 
		error("ERROR opening socket\n");
	bzero((char *) &serv_addr, sizeof(serv_addr));
	portno = atoi(argv[1]);
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(portno);
	if (bind(sockfd, (struct sockaddr *) &serv_addr,
		sizeof(serv_addr)) < 0) 
		error("ERROR on binding\n");
	listen(sockfd,5);
	clilen = sizeof(cli_addr);

	

	/* Modo Server esperando conexao Nivel 3 */
	while(flag<2)
	{
		/* Cria conexao */
		newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
		if (newsockfd < 0) 
			error("ERROR on accept\n");
		else if(newsockfd > 0)
		{
			if(flag==0)
				gettimeofday(&inicio,NULL);

			printf("Nova Conexao\n");
			n = read(newsockfd,buffer[flag],sizeof(buffern));
			flag++;

		}
		
		if (n < 0) error("ERROR reading from socket\n");
		close(newsockfd);
	}
	gettimeofday(&final, NULL);
	temposort = (final.tv_sec-inicio.tv_sec)*1000000 + final.tv_usec-inicio.tv_usec; /* Tempo calculado da comunicaçao com o Nivel 3 */
	printf("tempo comunicacao(ms): %lu\n", temposort);   	


	int k=0;
	
	/* Passando os vetores entradas para o vetor que sera ordenado */
	for(k=0;k<2;k++)
		for(i=0;i<TAMVET/2;i++)
		{	
			if(k==0)
				buffern[i]=buffer[k][i];
			else 
				buffern[(TAMVET/2)+i]=buffer[k][i];							
		}

	k=0;
	
	/* Copia do vetor original */
	for(k=0;k<TAMVET;k++)
		buffercopy[k]=buffern[k];

	sort(buffern);

	//for(k=0;k<TAMVET;k++)
		//printf("\n%d Indice %d",buffern[k],k);	

	printf("\n\n");

	enviar(buffern);
	return 0; 
}


